import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'

const whiteList = ['/login' || '/404']
router.beforeEach((to, from, next) => {
  // 拼接title  getPageTitle封装好的方法
  document.title = getPageTitle(to.meta.title)
  next()
})

router.beforeEach(async(to, from, next) => {
  // document.title = getPageTitle(to.meta.title)

  NProgress.start()
  const token = store.state.user.token
  const userId = store.state.user.userInfo.userId
  if (token) {
    if (whiteList.includes(to.path)) {
      console.log('用户登录，不能去login')
      next('/')
      NProgress.done()
    } else {
      // 1. 获取个人信息
      if (!userId) {
        await store.dispatch('user/getUserInfo')
      }

      next()
    }
  } else {
    //   没有token，只能访问白名单
    // includes用来查找数据中符合要求的
    // 如果没有登录就让去login
    if (whiteList.includes(to.path)) {
      next()
    } else {
      console.log('没有token，只能访问白名单')
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  NProgress.done()
})

